# __author__ : htzs
# __time__   : 19-5-29 下午1:00

import datetime
import json
import operator

from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.views.generic.base import View
from django.db.models import Q
from .serializers import ImageSerializers, NewThreeSerializers
from apps.maps.models import Map
from apps.video.models import Warn_model
from apps.warnlist.models import WarnModel
from apps.public.models import HwHttp, ZwHttp1, ZwHttp2

from utils import restful
from utils.top_datas import top_return


class SmallDataView(View):
    """
    返回首页小圈数据
    """

    def get(self, request):
        type = int(request.GET.get('type', 1))
        try:
            warn_sum = WarnModel.objects.all()
            all_data = warn_sum.count()  # 总数
        except Exception as e:
            return restful.params_error(message=e)
        else:
            if type == 1:
                sp_data = warn_sum.filter(warn_manage=9).count()  # 抛物

                try:
                    sum = '%.1f%%' % ((sp_data / all_data) * 100)

                except ZeroDivisionError:
                    sum = '0.0%'

                data = [
                    {
                        'value': sp_data,
                        'name': '抛物预警'
                    },
                    {
                        'value': all_data - sp_data,
                        'name': '泼水预警'
                    },
                    {
                        'score': sum
                    }
                ]
                return restful.result(data=data)
            elif type == 2:
                th_data = warn_sum.filter(warn_manage=10).count()  # 泼水
                try:
                    sum = '%.1f%%' % ((th_data / all_data) * 100)

                except ZeroDivisionError:
                    sum = '0.0%'
                data = [
                    {
                        'value': th_data,
                        'name': '泼水预警'
                    },
                    {
                        'value': all_data - th_data,
                        'name': '抛物预警'
                    },
                    {
                        'score': sum
                    }
                ]
                return restful.result(data=data)


class TopThreeView(View):
    """
    返回top3预警数据
    """

    def get(self, request):
        data = top_return(Warn_model, 3)
        return restful.result(data=data)


class EventTypeView(View):
    """
    返回事件类型数据
    """

    def get(self, request):
        warn_data = WarnModel.objects.all()
        alarm_no = warn_data.filter(alarm_score=0).count()
        alarm_yes = warn_data.filter(alarm_score=1).count()
        data = [
            {
                'value': alarm_yes,
                'name': '正常上报'
            },
            {
                'value': alarm_no,
                'name': '疑似事件',
            }
        ]
        return restful.result(data=data)


class LineDataView(View):
    """
    左下柱状图数据
    """

    def get(self, request):
        index = request.GET.get('index', 0)
        index = int(index)
        if index == 0:
            data_list = [{'已丢弃': 2, '已完成': 6, 'product': '0点'}, {'已丢弃': 9, '已完成': 8, 'product': '2点'},
                         {'已丢弃': 3, '已完成': 6, 'product': '4点'}, {'已丢弃': 8, '已完成': 0, 'product': '6点'},
                         {'已丢弃': 4, '已完成': 5, 'product': '8点'}, {'已丢弃': 8, '已完成': 5, 'product': '10点'},
                         {'已丢弃': 5, '已完成': 2, 'product': '12点'}, {'已丢弃': 4, '已完成': 6, 'product': '14点'},
                         {'已丢弃': 3, '已完成': 2, 'product': '16点'}, {'已丢弃': 6, '已完成': 8, 'product': '18点'},
                         {'已丢弃': 2, '已完成': 1, 'product': '20点'}, {'已丢弃': 5, '已完成': 8, 'product': '22点'}]
            return restful.result(data=data_list)

        elif index == 1:
            # 近七天数据
            now_week = datetime.datetime.now().isocalendar()[1]
            filter_data = WarnModel.objects.filter(
                add_time__week=now_week).values(
                'is_make', 'add_time').exclude(is_make__in=[1, 2])
            data_list = []
            data1 = filter_data.filter(is_make=3)
            data2 = filter_data.filter(Q(is_make=4) | Q(is_make=5))
            for i in range(2, 8):
                filter_data1 = data1.filter(add_time__week_day=i).count()
                filter_data2 = data2.filter(add_time__week_day=i).count()
                num_list = ['一', '二', '三', '四', '五', '六', '日']
                data = {
                    'product': '周{num_list[{0} - 2]}'.format(i),
                    '已完成': filter_data1,
                    '已丢弃': filter_data2
                }
                data_list.append(data)
            filter_data1 = data1.filter(add_time__week_day=1).count()
            filter_data2 = data2.filter(add_time__week_day=1).count()
            data = {'product': '周日', '已完成': filter_data1, '已丢弃': filter_data2}
            data_list.append(data)
            return restful.result(data=data_list)

        elif index == 2:
            # 按月统计
            month_data = WarnModel.objects.values(
                'is_make', 'add_time').exclude(is_make__in=[1, 2])
            data_list = []
            data1 = month_data.filter(is_make=3)
            data2 = month_data.filter(Q(is_make=4) | Q(is_make=5))
            for i in range(1, 13):
                filter_data1 = data1.filter(add_time__month=i).count()
                filter_data2 = data2.filter(add_time__month=i).count()
                data = {
                    'product': '{0}月'.format(i),
                    '已完成': filter_data1,
                    '已丢弃': filter_data2
                }
                data_list.append(data)
            return restful.result(data=data_list)
        return restful.result()


class ColumnDataView(View):
    """
    右下柱状图统计
    """

    def get(self, request):
        index = request.GET.get('index', 0)
        index = int(index)
        if index == 0:
            data_list = [{'product': '0点', '周界入侵': 5, '未穿工装': 6}, {'product': '2点', '周界入侵': 2, '未穿工装': 2},
                         {'product': '4点', '周界入侵': 6, '未穿工装': 5}, {'product': '6点', '周界入侵': 2, '未穿工装': 3},
                         {'product': '8点', '周界入侵': 5, '未穿工装': 5}, {'product': '10点', '周界入侵': 1, '未穿工装': 2},
                         {'product': '12点', '周界入侵': 3, '未穿工装': 1}, {'product': '14点', '周界入侵': 3, '未穿工装': 3},
                         {'product': '16点', '周界入侵': 2, '未穿工装': 5}, {'product': '18点', '周界入侵': 4, '未穿工装': 4},
                         {'product': '20点', '周界入侵': 2, '未穿工装': 2}, {'product': '22点', '周界入侵': 5, '未穿工装': 1}]
            return restful.result(data=data_list)

        elif index == 1:
            # 近七天数据
            now_week = datetime.datetime.now().isocalendar()[1]
            filter_data = WarnModel.objects.filter(
                add_time__week=now_week).values('warn_manage', 'add_time')
            data_list = []
            data1 = filter_data.filter(warn_manage=9)
            data2 = filter_data.filter(warn_manage=10)
            for i in range(2, 8):
                filter_data1 = data1.filter(add_time__week_day=i).count()
                filter_data2 = data2.filter(add_time__week_day=i).count()
                num_list = ['一', '二', '三', '四', '五', '六', '日']
                data = {
                    'product': '周{num_list[{0} - 2]}'.format(i),
                    '抛物预警': filter_data1,
                    '泼水预警': filter_data2
                }
                data_list.append(data)
            filter_data1 = data1.filter(add_time__week_day=1).count()
            filter_data2 = data2.filter(add_time__week_day=1).count()
            data = {
                'product': '周日',
                '抛物预警': filter_data1,
                '泼水预警': filter_data2
            }
            data_list.append(data)
            return restful.result(data=data_list)

        elif index == 2:
            # 按月统计
            month_data = WarnModel.objects.values('warn_manage', 'add_time')
            data_list = []
            data1 = month_data.filter(warn_manage=9)
            data2 = month_data.filter(warn_manage=10)
            for i in range(1, 13):
                filter_data1 = data1.filter(add_time__month=i).count()
                filter_data2 = data2.filter(add_time__month=i).count()
                data = {
                    'product': '{0}月'.format(i),
                    '抛物预警': filter_data1,
                    '泼水预警': filter_data2
                }
                data_list.append(data)
            return restful.result(data=data_list)
        return restful.result()


class IndexDataView(View):
    """
    数据大屏 -- 各种统计数据
    """

    def _data(self, rec_data, send_data, num):
        data1 = 0
        try:
            data_1 = '%.2f%%' % ((rec_data / send_data) * 100)

        except ZeroDivisionError:
            data_1 = '0.00%'
        else:
            data1 = int(eval(data_1.strip('%')))
        context = {
            'data_{0}'.format(num): data_1,
            'data{0}'.format(num): data1,
        }
        return context

    def line_data(self, x, y):
        try:
            sum = '%.1f%%' % ((x / y) * 100)

        except ZeroDivisionError:
            sum = '0.0%'
        return sum

    def get(self, request):
        """
        各种统计数据
        :param request:
        :return:
        """
        # 来源统计分析数据
        warns = WarnModel.objects.all()
        warn_z = warns.filter(warn_type=1).count()
        warn_s = warns.filter(warn_type=2).count()
        all_warns = warn_z + warn_s

        result_1 = self.line_data(warn_z, all_warns)
        result_2 = self.line_data(warn_s, all_warns)

        #  the end...

        now_week = datetime.datetime.now().isocalendar()[1]
        warns = WarnModel.objects.filter(add_time__week=now_week)

        send_data1 = warns.filter(~(Q(is_make=1) | Q(is_make=5))).count()

        # 城管 -- 完结率
        rec_data2 = warns.filter(is_make=3).count()
        send_data2 = send_data1
        context2 = self._data(rec_data2, send_data2, 2)

        # 城管 -- 丢弃率
        rec_data3 = warns.filter(is_make=4).count()
        send_data3 = send_data1
        context3 = self._data(rec_data3, send_data3, 3)
        context2.update(context3)

        # 待办预警
        today = datetime.date.today()
        today_data = warns.filter(add_time__gte=today)
        today_rec = today_data.filter(is_make=1).count()

        # 上报城管
        today_send = today_data.filter(Q(is_make=2) | Q(is_make=3) | Q(is_make=4)).count()

        # 城管办理
        today_make = today_data.filter(is_make=3).count()

        # 监控总数 / 在线监控
        map_all = Map.objects.all().count()
        map_alive = Map.objects.filter(status=1).count()

        # 今日总计
        today = datetime.date.today()
        today_datas = WarnModel.objects.filter(add_time__gte=today)
        today_warns = today_datas.count()
        today_1 = today_datas.filter(warn_manage=10).count()
        today_2 = today_datas.filter(warn_manage=9).count()

        if today_1 >= today_2:
            name = '泼水'
        else:
            name = '抛撒'

        # 待办预警
        need_make = WarnModel.objects.filter(is_make=1)
        send_warns = need_make.count()
        now_warns = need_make.filter(add_time__gte=today).count()
        others = send_warns - now_warns

        warn_sum = Warn_model.objects.all().count()

        image = Warn_model.objects.order_by('-add_time').first()

        warns = Warn_model.objects.order_by('-add_time')[:5]

        sum_data = {
            'all_warns': all_warns,
            'warn_z': warn_z,
            'warn_s': warn_s,
            'result_1': result_1,
            'result_2': result_2,
            'today_rec': today_rec,
            'today_send': today_send,
            'today_make': today_make,
            'map_all': map_all,
            'map_alive': map_alive,
            'today_warns': today_warns,
            'send_warns': send_warns,
            'name': name,
            'others': others,
            'warn_sum': warn_sum,
            'image': image,
            'warns': warns
        }
        context2.update(sum_data)
        result = float(eval(context2['data_2'].strip('%'))) + float(eval(context3['data_3'].strip('%')))
        context2['data_5'] = str(result) + '{}'.format('%')
        context2['data5'] = context2['data2'] + context2['data3']
        return render(request, 'public/data-tv.html', context=context2)
        # print(context2)
        # return restful.result(data=context2)


# 首页左下角日期筛选
class IndexTimeView(View):
    def get(self, request):
        times = request.GET.get('times', '')
        if times:
            start_time = datetime.datetime.strptime(times[:10], '%Y-%m-%d')
            end_time = datetime.datetime.strptime(times[13:23], '%Y-%m-%d')
            end_times = datetime.datetime.strptime(times[13:23], '%Y-%m-%d') + datetime.timedelta(days=1)
            days = (end_time - start_time).days
            filter_data = WarnModel.objects.filter(add_time__range=(start_time, end_times)).values(
                'is_make', 'add_time').exclude(is_make__in=[1, 2])
            data1 = filter_data.filter(is_make=3)
            data2 = filter_data.filter(Q(is_make=4) | Q(is_make=5))
            data_list = []
            for i in range(0, days + 1):
                sum_time = start_time + datetime.timedelta(days=i)
                filter_data1 = data1.filter(add_time__date=sum_time).count()
                filter_data2 = data2.filter(add_time__date=sum_time).count()
                data = {
                    'product': '{0}/{1}'.format(sum_time.month, sum_time.day),
                    '已完成': filter_data1,
                    '已丢弃': filter_data2
                }
                data_list.append(data)
            return restful.result(data=data_list)
        else:
            return restful.params_error(message='请先选择日期,再提交!')


# 首页右下角日期筛选
class IndexTimesView(View):
    def get(self, request):
        times = request.GET.get('times', '')
        if times:
            start_time = datetime.datetime.strptime(times[:10], '%Y-%m-%d')
            end_time = datetime.datetime.strptime(times[13:23], '%Y-%m-%d')
            end_times = datetime.datetime.strptime(times[13:23], '%Y-%m-%d') + datetime.timedelta(days=1)
            days = (end_time - start_time).days
            filter_data = WarnModel.objects.filter(add_time__range=(start_time, end_times)).values(
                'warn_manage', 'add_time')
            data1 = filter_data.filter(warn_manage=9)
            data2 = filter_data.filter(warn_manage=10)
            data_list = []
            for i in range(0, days + 1):
                sum_time = start_time + datetime.timedelta(days=i)
                filter_data1 = data1.filter(add_time__date=sum_time).count()
                filter_data2 = data2.filter(add_time__date=sum_time).count()
                data = {
                    'product': '{0}/{1}'.format(sum_time.month, sum_time.day),
                    '抛物预警': filter_data1,
                    '泼水预警': filter_data2
                }
                data_list.append(data)
            return restful.result(data=data_list)
        else:
            return restful.params_error(message='请先选择日期,再提交!')


class LineTopView(View):
    """
    返回数据大屏左下角过去7天top3
    """

    def get(self, request):
        """
        # 找出过去7天,前3监控点预警总数
        :param data:
        :param models:
        :return:
        """
        last_data = [
            {'展会中心1': [5, 6, 8, 2, 1, 5, 5]}, {'12楼客梯厅': [11, 2, 5, 3, 8, 6, 9]}, {'出口违停球': [12, 5, 8, 4, 6, 10, 7]},
            ['周一', '周二', '周三', '周四', '周五', '周六', '周日']]
        return restful.result(data=last_data)


class HttpDataView(View):
    """
    返回数据
    """

    def get(self, request):
        try:
            type = request.GET.get('type', '1')
        except:
            return restful.params_error(message='参数有误.')
        type = int(type)
        try:
            if type == 1:
                http_request = HwHttp.objects.filter(type=1).count()
                http_response = HwHttp.objects.filter(type=2).count()
                stop_time = HwHttp.objects.all().first().add_time
                start_time = HwHttp.objects.all().last().add_time
                data = {
                    '华为预警请求': http_request,
                    '平台响应': http_response,
                    '统计开始时间': start_time,
                    '统计结束时间': stop_time
                }
                return restful.result(data=data, message='success')
            elif type == 2:
                http_rec_request = ZwHttp1.objects.filter(type=1).count()
                http_rec_response = ZwHttp1.objects.filter(type=2).count()
                stop_time = ZwHttp1.objects.all().first().add_time
                start_time = ZwHttp1.objects.all().last().add_time
                data_1 = {
                    '接收中威响应': http_rec_request,
                    '平台响应': http_rec_response,
                    '统计开始时间': start_time,
                    '统计结束时间': stop_time
                }
                http_pic_request = ZwHttp2.objects.filter(
                    Q(category=1) & Q(type=1)).count()
                http_pic_response = ZwHttp2.objects.filter(
                    Q(category=1) & Q(type=2)).count()
                http_video_request = ZwHttp2.objects.filter(
                    Q(category=2) & Q(type=1)).count()
                http_video_response = ZwHttp2.objects.filter(
                    Q(category=2) & Q(type=2)).count()
                stop_time = ZwHttp2.objects.all().first().add_time
                start_time = ZwHttp2.objects.all().last().add_time
                data_2 = {
                    '截图请求': http_pic_request,
                    '截图响应': http_pic_response,
                    '视频请求': http_video_request,
                    '视频响应': http_video_response,
                    '统计开始时间': start_time,
                    '统计结束时间': stop_time
                }

                data = {'中威请求平台': data_1, '平台请求截图/视频': data_2}

                return restful.result(data=data, message='success')
        except:
            return restful.result(message='type参数仅为1和2')
        return restful.result(message='type参数仅为1和2')


# class CakeDataView(View):
#     """
#     蛋糕图统计
#     """
#
#     def get(self, request):
#         # 1天数据 - 每隔6小时统计一次
#         today = datetime.date.today()
#         today_data = WarnModel.objects.filter(add_time__gte=today).values(
#             'warn_manage', 'add_time')
#         data_list1 = []
#         data_list2 = []
#         data1 = today_data.filter(warn_manage=9)
#         data2 = today_data.filter(warn_manage=10)
#
#         time_list = [0, 6, 12, 18]
#         for i in time_list:
#             select_data1 = data1.filter(add_time__hour__range=(i,
#                                                                i + 6)).count()
#             select_data2 = data2.filter(add_time__hour__range=(i,
#                                                                i + 6)).count()
#             data_list1.append(select_data1)
#             data_list2.append(select_data2)
#         data = {'Spilling': data_list1, 'water': data_list2}
#         return restful.result(data=data)
class FlushView(View):
    '''用作刷新的data返回'''

    def get(self, request):
        warns_count = Warn_model.objects.all().count()
        # 动态获取前两位
        zj_count = Warn_model.objects.filter(type="周界入侵报警抓拍").count()
        # 打手机，周界入侵，未戴安全帽
        dsj_count = Warn_model.objects.filter(type="打手机").count()
        # wcgz_count = Warn_model.objects.filter(type="未穿工服抓拍").count()
        wdaqm_count = Warn_model.objects.filter(type="未戴安全帽抓拍").count()

        dict = {
            "周界入侵": zj_count,
            "打手机": dsj_count,
            "未戴安全帽": wdaqm_count
        }
        # print(dict)
        list = sorted(dict.items(), key=operator.itemgetter(1))
        # print(list)
        first_type = list[-1]
        # print(type(first_type))
        # print(first_type[0])
        second_type = list[-2]

        data = {
            "warn_sum": warns_count,
            "zj_count": zj_count,
            "dsj_count": dsj_count,
            "wdaqm_count": wdaqm_count,
            "first_type": first_type[0],
            "second_type": second_type[0],
            "most_count":first_type[1],
            "second_count":second_type[1]
            # "new_image":new_image
        }
        # print(data)
        # data = new_image.data
        return restful.result(data=data)
        # return HttpResponse(json.dumps(data), content_type='application/json')


class ImageView(View):
    def get(self, request):
        object_new = Warn_model.objects.all().order_by('-add_time').first()
        # print(object_new.image)

        # new_image = object_new
        new_image = ImageSerializers(object_new)
        data = new_image.data
        # print(data)
        return restful.result(data=data)


class NewThreeView(View):
    def get(self, request):
        new_three = Warn_model.objects.order_by("-add_time")[:3]
        data = NewThreeSerializers(new_three, many=True).data
        # print(data)
        return restful.result(data=data)
